import { autoOpenSettingWhenNeedAuth } from '../../../utils/openSetting';
import { saveVideoToPhotosAlbum, chooseVideo } from '../../../utils/wxApis';
import upload from '../../../utils/upload';

const MAX_DURATION = 20;

Page({
  data: {
    videoUrl: '',
    videoInfo: null,
    uploadResult: null,
    danmuList: [
      {
        text: '第 1s 出现的弹幕',
        color: '#ff0000',
        time: 1,
      },
      {
        text: '第 2s 出现的弹幕',
        color: '#00ff00',
        time: 2,
      },
      {
        text: '第 3s 出现的弹幕',
        color: '#0000ff',
        time: 3,
      },
      {
        text: '第 4s 出现的弹幕',
        color: '#fff000',
        time: 4,
      }],
  },
  async uploadVideo() {
    if (!this.data.videoUrl) {
      return;
    }
    try {
      const uploadResult = await upload(this.data.videoUrl);
      console.log(uploadResult);
      this.setData({
        uploadResult: JSON.stringify(uploadResult, null, 2),
      });
    } catch (error) {
      console.error(error);
    }
  },

  async chooseVideo() {
    try {
      const res = await autoOpenSettingWhenNeedAuth(chooseVideo.bind(undefined, {
        compressed: true,
        maxDuration: MAX_DURATION,
        camera: 'front',
      }));

      console.log(res);
      res.size = `${res.size / 1024}kb`;
      res.duration = `${res.duration}s`;
      this.setData({
        videoUrl: res.tempFilePath,
        videoInfo: res,
      });
    } catch (error) {
      console.error(error);
    }
  },

  async saveVideoToPhotosAlbum() {
    try {
      await autoOpenSettingWhenNeedAuth(saveVideoToPhotosAlbum.bind(undefined, {
        filePath: this.data.videoUrl,
      }));
    } catch (error) {
      console.error(error);
    }
  },
});
